/* socketHelper.c */

#include <stdio.h>
#include "socketHelper.h"

/* Function: initListenSocket
* Usage: result = initListenSocket(&listenInfo, &listenSocket, getHttpPort());
* -------------------------------- 
* This function initializes the listen socket. It will create a socket, bind and listen. If it fails to initialize
* the socket in any way it will return SOCKET_ERROR, else it will return 1 (which means that it succeeded).
*/ 
int initListenSocket(SOCKADDR_IN *listenInfo, SOCKET *listenSocket, int port) {
	int result;

	initListenInfo(listenInfo, port);

	*listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (*listenSocket == INVALID_SOCKET) {
		printf("Listen socket failed\n");
		return SOCKET_ERROR;
	}
	result = bind(*listenSocket, (SOCKADDR *)listenInfo, sizeof(*listenInfo));
	if (result == SOCKET_ERROR) {
		printf("Binding listensocket failed\n");
		return SOCKET_ERROR;
	}
	result = listen(*listenSocket, SOMAXCONN);
	if (result == SOCKET_ERROR) {
		printf("Listensocket failed to listen\n");
		return SOCKET_ERROR;
	}
	return 1;
}

/* Function: initListenInfo
* Usage: initListenInfo(listenInfo, port);
* -------------------------------- 
* This function initializes the struct listenInfo by giving it some default values.
*/ 
void initListenInfo(SOCKADDR_IN *listenInfo, int port) {
	listenInfo->sin_family = AF_INET;
	listenInfo->sin_port = htons(port);
	listenInfo->sin_addr.s_addr = INADDR_ANY;
}
